﻿using System;
using System.Collections.Generic;

namespace BlamanticUI.Components;

/// <summary>
/// Represents a container to display toast message.
/// </summary>
[CssClass("toast-container")]
public class ToastContainer : BlazorComponentBase, IHasUIComponent,IDisposable
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ToastContainer"/> class.
    /// </summary>
    public ToastContainer()
    {
    }

    /// <summary>
    /// Gets or sets the toast service.
    /// </summary>
    [Inject] IToastService ToastService { get; set; }

    [Parameter] public DockPosition Position { get; set; } = DockPosition.TopCenter;

    [Parameter]public string Key { get; set; } = "Default";

    protected override void OnParametersSet()
    {
        if (string.IsNullOrWhiteSpace(Key))
        {
            throw new ArgumentException("Container must have a value for Key", nameof(Key));
        }
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        ToastService.OnToastUpdating += () => NotifyStateChanged();
    }

    //protected override void BuildRenderTree(RenderTreeBuilder builder)
    //{
    //    builder.OpenRegion(RegionSequence);
    //    builder.OpenElement(0, "div");
    //    AddClassAttribute(builder, 1);
    //    AddContent(builder, 2);
    //    builder.CloseElement();
    //    builder.CloseRegion();
    //}

    protected override void AddContent(RenderTreeBuilder builder, int sequence)
    {
        if (ToastService.Toasters.ContainsKey(Key))
        {

            foreach (var controller in ToastService.Toasters[Key])
            {
                builder.OpenRegion(sequence + 1);
                builder.OpenComponent<ToastBox>(1);
                builder.AddAttribute(2, nameof(ToastBox.Controller), controller);
                builder.CloseComponent();
                builder.CloseRegion();

                //builder.CreateComponent<ToastBox>(sequence + 1, attributes: new { Controller = controller }, appendFunc: (append, sequence) =>
                //    {
                //        append.SetKey(controller);
                //        return sequence;
                //    });
            }
        }
    }

    protected override void BuildCssClass(ICssClassBuilder builder)
{
        builder.Append(Position.GetCssClass());
    }

    public void Dispose()
    {
        ToastService.OnToastUpdating -= () => NotifyStateChanged();
    }
}
